﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;

namespace Repo.DataAccess
{
    public class Collector
    {
        public static IEnumerable<SPListItem> CollectItems(
            SPSite site,
            SPContentType contentType,
            string listTitle)
        {
            var items = new List<SPListItem>();
            var lists = SPContentTypeUsage.GetUsages(contentType);
            foreach (SPContentTypeUsage spContentTypeUsage in lists)
            {
                if (spContentTypeUsage.IsUrlToList)
                {
                    var list = site.AllWebs["/"].GetList(spContentTypeUsage.Url);
                    if (list != null)
                    {
                        if (!string.IsNullOrEmpty(listTitle) && list.Title != listTitle)
                        {
                            continue;
                        }
                        var query = new SPQuery
                        {
                            Query = string.Concat(
                                "<Where><Eq>",
                                "<FieldRef Name='ContentType'/>",
                                string.Format("<Value Type='Text'>{0}</Value>", contentType.Name),
                                "</Eq></Where>")
                        };
                        items.AddRange(list.GetItems(query).Cast<SPListItem>());
                        foreach (SPListItem listItem in list.Folders)
                        {
                            query.Folder = listItem.Folder;
                            items.AddRange(list.GetItems(query).Cast<SPListItem>());
                        }
                    }
                }
            }
            return items;
        }
    }
}
